import { reqLogin } from "../../request/api"
import { myAlert } from "../../utils/alert"

/* 状态 */
const initState = {
    user: {
        phone:"",
        password:""
    },
    //用户信息
    info: sessionStorage.getItem("info") ? JSON.parse(sessionStorage.getItem("info")) : {}
}

const TYPES = {
    /* 修改user的type */
    LOGIN_CHANGE_USER: "LOGIN-CHANGE_USER",
    LOGIN_CHANGE_INFO: "LOGIN_CHANGE_INFO"
}

export const actions = {
    /* 修改 user的action */

    changeUser: (value, key) => ({ type: TYPES.LOGIN_CHANGE_USER, value, key }),
    //修改 info
    changeInfo: (info) => {
        if (info.uid) {
            sessionStorage.setItem("info", JSON.stringify(info))
        } else {
            sessionStorage.removeItem("info")
        }
        return { type: TYPES.LOGIN_CHANGE_INFO, info }
    },
    //登录请求
    reqLogin: (router) => {
        return (dispatch, getState) => {
            let { user } = getState().login;
            reqLogin(user).then(res => {
                //判断是否成功
                if (res.data.code === 200) {
                    console.log(router);
                    //1.弹成功
                    myAlert(res.data.msg)
                    //2.res.list存起来  本地存储存一份，redux存一份
                    dispatch(actions.changeInfo(res.data.list))
                    //3.跳转页面
                    router.push("/index/home")
                }
            })
        }
    },
    reqLon:(router)=>{
        return(dispatch,getState)=>{
            router.push("/register")
        }
    }
    

}


//reducer

const reducer = (state = initState, action) => {
    switch (action.type) {
        //修改user
        case TYPES.LOGIN_CHANGE_USER:
            return {
                ...state,
                user: {
                    ...state.user,
                    [action.key]: action.value
                }
            }
        case TYPES.LOGIN_CHANGE_INFO:
            return {
                ...state,
                info: action.info
            }

        default:
            return state
    }
}
export default reducer
//selector
//用户输入值
export const getUser = state => state.login.user;

//用户信息
export const getInfo = state => state.login.info
